package com.jwater.core.manager.worker;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jwater.core.common.InitLogger;
import com.jwater.core.common.IpPort;
import com.jwater.core.common.JvmNames;
import com.jwater.core.manager.common.conf.CoreConfParse;
import com.jwater.core.manager.common.model.WorkerInfo;
import com.jwater.core.metrics.JvmMetric;
import com.jwater.core.utils.ProcessUtils;
import com.jwater.launch.Jwater;

/**
 * @description:worker启动入口类
 * @author: jnner
 * @createDate: 2021/2/5
 * @version: 1.0
 */
public class WorkerMain {
    protected static Logger logger = LoggerFactory.getLogger(WorkerMain.class);

    public static void killOld(String regionName, String deployName, String groupName, String workerName, int index,
                               CoreConfParse conf) {
        int currId = JvmMetric.pid();
        logger.info("currId:" + currId);
        List<Integer> ids = ProcessUtils.getProcessIds(Jwater.class.getName(),
                JvmNames.getWorkerName(conf.getClusterName(), regionName, deployName, groupName, workerName, index));
        for (Integer id : ids) {
            if (id != currId) {
                try {
                    ProcessUtils.killById(id, true);
                } catch (Exception e) {
                    logger.error(e.toString(), e);
                }
            }
        }
    }

    public static void main(String[] args) {
        String host = args[0];
        String regionName = args[1];
        String deployName = args[2];
        String groupName = args[3];
        String workerName = args[4];
        int index = Integer.parseInt(args[5]);
        InitLogger.initWorker(regionName, deployName, groupName, workerName, index);
        CoreConfParse coreConfParse = new CoreConfParse();
        coreConfParse.parse();
        killOld(regionName, deployName, groupName, workerName, index, coreConfParse);
        WorkerInfo workerInfo = new WorkerInfo();
        workerInfo.setRegionName(regionName);
        workerInfo.setDeployName(deployName);
        workerInfo.setGroupName(groupName);
        workerInfo.setWorkerName(workerName);
        try {
            List<IpPort> masterHosts = coreConfParse.getMasterHosts();
            WorkerNode workerNode = new WorkerNodeImpl(host, masterHosts, workerInfo, index);
            workerNode.start();
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
    }

}
